package com.xingjiejian.feature.lambda;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 使用lambda表达式和函数式接口Predicate
 * 1. lambda表达式构建Predicate对象
 * 2. 合并组装多个Predicate对象
 *
 * Predicate：
 *    作用：判断对象是否符合某个条件
 *    使用场景：
 *      1)ArrayList的removeIf(Predicate)：删除符合条件的元素
 *      2)Stream对象的filter(Predicate)：过滤集合中符合条件的元素
 * @author XingJiejian
 * @date 2019/5/7 0007
 */
public class Demo5 {
    /**
     * 筛选过滤集合中的数据并输出
     * @param names
     * @param condition
     */
    public static void filter(List<String> names, Predicate<String> condition) {
        //之前的做法
//        for(String name: names)  {
//            if(condition.test(name)) {
//                System.out.println(name + " ");
//            }
//        }

        //java 8之后的做法
        names.stream().filter((name) -> (condition.test(name))).forEach((name) -> {
            System.out.println(name + " ");
        });
    }

    public static void main(String[] args) {
        List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");

        System.out.println("Languages which starts with J :");
        // (str)->str.startsWith("J")
        // 相当于 Predicate<String> startsWithJ = (str)->str.startsWith("J")
        filter(languages, (str)->str.startsWith("J"));

        System.out.println("Languages which ends with a ");
        filter(languages, (str)->str.endsWith("a"));

        System.out.println("Print all languages :");
        filter(languages, (str)->true);

        System.out.println("Print no language : ");
        filter(languages, (str)->false);

        System.out.println("Print language whose length greater than 4:");
        filter(languages, (str)->str.length() > 4);


        // 甚至多个Predicate条件可以用and()、or()和xor()逻辑函数来合并
        // 类似于逻辑操作符AND和OR
        Predicate<String> startsWithJ = (n) -> n.startsWith("J");
        Predicate<String> fourLetterLong = (n) -> n.length() == 4;
        languages.stream()
                .filter(startsWithJ.and(fourLetterLong))
                .forEach((n) -> System.out.print("nName, which starts with 'J' and four letter long is : " + n));


    }
}
